<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能温控系统</title>
    <script src="./lib/tailwindcss.js"></script>
    <link href="./lib/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <script src="./lib/chart.umd.min.js"></script>
    <!-- 引入加密库 -->
    <script src="./lib/crypto-js.min.js"></script>
    
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        accent: '#FF7D00',
                        cold: '#4096ff',
                        hot: '#f5222d',
                        neutral: '#f5f5f5',
                        dark: '#1f2937'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .shadow-soft {
                box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
            }
            .gradient-bg {
                background: linear-gradient(135deg, #f5f7fa 0%, #e5e9f2 100%);
            }
            .card-hover {
                transition: all 0.3s ease;
            }
            .card-hover:hover {
                transform: translateY(-5px);
            }
			.auto-refresh-indicator {
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0% { opacity: 0.6; }
                50% { opacity: 1; }
                100% { opacity: 0.6; }
            }
        }
    </style>
</head>
<body class="gradient-bg min-h-screen font-sans text-dark">
    <!-- 顶部导航栏 -->
    <header class="bg-white/80 backdrop-blur-md shadow-sm sticky top-0 z-50 transition-all duration-300">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-thermometer-half text-primary text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold text-primary">智能温湿度监控与空调控制</h1>
            </div>
            <div class="flex items-center space-x-4">
                <span id="connection-status" class="hidden md:flex items-center text-sm">
                    <span class="w-2 h-2 rounded-full bg-red-500 mr-2"></span>
                    <span>未连接</span>
					<span id="auto-refresh-label" class="ml-2 text-xs text-gray-500 auto-refresh-indicator">(自动刷新中)</span>
                </span>
                <button id="refresh-btn" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-refresh text-primary"></i>
                </button>
                <button id="config-btn" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-cog text-primary"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 配置界面 (默认隐藏) -->
    <div id="config-panel" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-md p-6 transform transition-all">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold text-primary">巴法云配置</h2>
                <button id="close-config" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <form id="config-form" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">巴法云ID (clientId)</label>
                    <input type="text" id="client-id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="88888888">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">温湿度主题</label>
                    <input type="text" id="temp-topic" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="temp004">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">空调主题</label>
                    <input type="text" id="air-topic" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="aircd005">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">API密钥</label>
                    <input type="password" id="api-key" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="你的API密钥">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">加密密码 (用于配置导入导出)</label>
                    <input type="password" id="encrypt-password" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="设置加密密码">
                </div>
            </form>
            
            <div class="flex space-x-3 mt-6">
                <button id="export-config" class="flex-1 py-2 border border-primary text-primary rounded-lg hover:bg-primary/5 transition-colors">
                    <i class="fa fa-download mr-1"></i> 导出配置
                </button>
                <button id="import-config" class="flex-1 py-2 border border-primary text-primary rounded-lg hover:bg-primary/5 transition-colors">
                    <i class="fa fa-upload mr-1"></i> 导入配置
                </button>
                <input type="file" id="import-file" accept=".bafa" class="hidden">
            </div>
            
            <div class="mt-4">
                <button id="save-config" class="w-full py-3 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition-colors">
                    保存配置
                </button>
            </div>
        </div>
    </div>

    <main class="container mx-auto px-4 py-8">
        <!-- 状态概览卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <!-- 温度卡片 -->
            <div class="bg-white rounded-2xl shadow-soft p-6 card-hover">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h2 class="text-gray-500 font-medium">当前温度</h2>
                        <div class="flex items-end mt-2">
                            <span id="temperature" class="text-4xl font-bold">--</span>
                            <span class="text-2xl font-bold ml-1">°C</span>
                        </div>
                    </div>
                    <div class="p-3 rounded-full bg-blue-50">
                        <i class="fa fa-thermometer-half text-primary text-xl"></i>
                    </div>
                </div>
                <div class="flex items-center text-sm text-gray-500">
                    <i class="fa fa-clock-o mr-1"></i>
                    <span id="temp-update-time">未更新</span>
                </div>
            </div>
            
            <!-- 湿度卡片 -->
            <div class="bg-white rounded-2xl shadow-soft p-6 card-hover">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h2 class="text-gray-500 font-medium">当前湿度</h2>
                        <div class="flex items-end mt-2">
                            <span id="humidity" class="text-4xl font-bold">--</span>
                            <span class="text-2xl font-bold ml-1">%</span>
                        </div>
                    </div>
                    <div class="p-3 rounded-full bg-green-50">
                        <i class="fa fa-tint text-green-500 text-xl"></i>
                    </div>
                </div>
                <div class="flex items-center text-sm text-gray-500">
                    <i class="fa fa-clock-o mr-1"></i>
                    <span id="hum-update-time">未更新</span>
                </div>
            </div>
            
            <!-- 空调状态卡片 -->
            <div class="bg-white rounded-2xl shadow-soft p-6 card-hover">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h2 class="text-gray-500 font-medium">空调状态</h2>
                        <div class="mt-2">
                            <span id="ac-status" class="text-2xl font-bold text-gray-400">未开启</span>
                            <div id="ac-details" class="text-gray-500 mt-1 hidden">
                                <div>模式: <span id="ac-mode">制冷</span></div>
                                <div>温度: <span id="ac-temp">26°C</span></div>
								<div>风速: <span id="ac-fan">自动</span></div>
                            </div>
                        </div>
                    </div>
                    <div id="ac-icon" class="p-3 rounded-full bg-gray-50">
                        <i class="fa fa-snowflake-o text-gray-400 text-xl"></i>
                    </div>
                </div>
                <div class="flex items-center text-sm text-gray-500">
                    <i class="fa fa-signal mr-1"></i>
                    <span id="bafa-id-display">巴法云 ID: 未配置</span>
                </div>
            </div>
        </div>
        
        <!-- 图表和控制面板 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 温湿度历史图表 -->
            <div class="lg:col-span-1 bg-white rounded-2xl shadow-soft p-6">
                <h2 class="text-lg font-semibold mb-4">温湿度趋势</h2>
                <div class="h-64">
                    <canvas id="environment-chart"></canvas>
                </div>
                <div class="flex justify-center mt-4 space-x-4">
                    <button class="text-sm px-3 py-1 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors active-chart-period">24小时</button>
                    <button class="text-sm px-3 py-1 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors">7天</button>
                    <button class="text-sm px-3 py-1 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors">30天</button>
                </div>
            </div>
            
            <!-- 空调控制面板 -->
            <div class="lg:col-span-2 bg-white rounded-2xl shadow-soft p-6">
                <h2 class="text-lg font-semibold mb-6">空调控制</h2>
                
                <!-- 开关控制 -->
                <div class="flex items-center justify-between mb-8">
                    <span class="text-lg font-medium">电源</span>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" id="ac-power" class="sr-only peer">
                        <div class="w-14 h-7 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-6 after:w-6 after:transition-all peer-checked:bg-primary"></div>
                    </label>
                </div>
                
                <!-- 模式选择 -->
                <div class="mb-8">
                    <span class="text-lg font-medium block mb-3">运行模式</span>
                    <div class="grid grid-cols-5 gap-3">
                        <button class="ac-mode-btn active" data-mode="auto">
                            <i class="fa fa-refresh block text-center text-lg mb-1"></i>
                            <span class="text-sm">自动</span>
                        </button>
                        <button class="ac-mode-btn" data-mode="cool">
                            <i class="fa fa-snowflake-o block text-center text-lg mb-1"></i>
                            <span class="text-sm">制冷</span>
                        </button>
                        <button class="ac-mode-btn" data-mode="dry">
                            <i class="fa fa-tint block text-center text-lg mb-1"></i>
                            <span class="text-sm">除湿</span>
                        </button>
                        <button class="ac-mode-btn" data-mode="fan">
                            <i class="fa fa-leaf block text-center text-lg mb-1"></i>
                            <span class="text-sm">通风</span>
                        </button>
                        <button class="ac-mode-btn" data-mode="heat">
                            <i class="fa fa-sun-o block text-center text-lg mb-1"></i>
                            <span class="text-sm">制热</span>
                        </button>
                    </div>
                </div>
                
                <!-- 温度调节 -->
                <div class="mb-8">
                    <span class="text-lg font-medium block mb-4">温度设置</span>
                    <div class="flex items-center justify-center">
                        <button id="temp-down" class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-xl">
                            <i class="fa fa-minus"></i>
                        </button>
                        <div class="mx-8">
                            <span id="set-temperature" class="text-4xl font-bold">26</span>
                            <span class="text-xl">°C</span>
                        </div>
                        <button id="temp-up" class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-xl">
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2 mt-6">
                        <div id="temp-slider" class="bg-primary h-2 rounded-full" style="width: 50%"></div>
                    </div>
                    <div class="flex justify-between text-xs text-gray-500 mt-1">
                        <span>16°C</span>
                        <span>30°C</span>
                    </div>
                </div>
                
                <!-- 风速调节 -->
                <div>
                    <span class="text-lg font-medium block mb-3">风速设置</span>
                    <div class="grid grid-cols-4 gap-3">
                        <button class="ac-fan-btn active" data-fan="auto">
                            <i class="fa fa-refresh block text-center text-lg mb-1"></i>
                            <span class="text-sm">自动</span>
                        </button>
                        <button class="ac-fan-btn" data-fan="low">
                            <i class="fa fa-wind block text-center text-lg mb-1"></i>
                            <span class="text-sm">低速</span>
                        </button>
                        <button class="ac-fan-btn" data-fan="medium">
                            <i class="fa fa-wind block text-center text-lg mb-1"></i>
                            <span class="text-sm">中速</span>
                        </button>
                        <button class="ac-fan-btn" data-fan="high">
                            <i class="fa fa-wind block text-center text-lg mb-1"></i>
                            <span class="text-sm">高速</span>
                        </button>
                    </div>
                </div>
                
                <!-- 确认按钮 -->
                <div class="mt-8">
                    <button id="send-command" class="w-full py-3 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition-colors flex items-center justify-center">
                        <i class="fa fa-paper-plane mr-2"></i>
                        发送控制指令
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 设备信息 -->
        <div class="mt-8 bg-white rounded-2xl shadow-soft p-6">
            <h2 class="text-lg font-semibold mb-4">设备信息</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="flex items-start">
                    <div class="p-2 rounded-full bg-blue-50 mr-3 mt-1">
                        <i class="fa fa-microchip text-primary"></i>
                    </div>
                    <div>
                        <h3 class="font-medium">传感器模块</h3>
                        <p class="text-gray-500 text-sm">ESP01S + AHT10温湿度传感器</p>
                    </div>
                </div>
                <div class="flex items-start">
                    <div class="p-2 rounded-full bg-blue-50 mr-3 mt-1">
                        <i class="fa fa-wifi text-primary"></i>
                    </div>
                    <div>
                        <h3 class="font-medium">连接方式</h3>
                        <p class="text-gray-500 text-sm">Wi-Fi连接至巴法云平台</p>
                    </div>
                </div>
                <div class="flex items-start">
                    <div class="p-2 rounded-full bg-blue-50 mr-3 mt-1">
                        <i class="fa fa-infrared text-primary"></i>
                    </div>
                    <div>
                        <h3 class="font-medium">控制方式</h3>
                        <p class="text-gray-500 text-sm">红外信号发送空调控制指令</p>
                    </div>
                </div>
                <div class="flex items-start">
                    <div class="p-2 rounded-full bg-blue-50 mr-3 mt-1">
                        <i class="fa fa-cloud text-primary"></i>
                    </div>
                    <div id="topics-display">
                        <h3 class="font-medium">巴法云主题</h3>
                        <p class="text-gray-500 text-sm">未配置</p>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <footer class="mt-12 py-6 border-t">
        <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
            <p>智能温湿度监控与空调控制系统 &copy; 2025</p>
        </div>
    </footer>

    <!-- 通知提示 -->
    <div id="notification" class="fixed bottom-6 right-6 bg-dark text-white px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center">
        <i id="notification-icon" class="fa fa-check-circle mr-2"></i>
        <span id="notification-text">操作成功</span>
    </div>

    <script>
	
	        // 全局变量
        let currentTemp = 26;
        let currentMode = 'cool';
        let currentFan = 'low';
		let isOnline = false;
        let isAcOn = false;
        let tempHistory = [];
        let humidityHistory = [];
        let timeLabels = [];
        let BAFA_CONFIG = {
            clientId: "",
            tempTopic: "",
            airTopic: "",
            apiKey: "",
            apiUrl: "https://apis.bemfa.com"
        };
	
	// 1. 独立的巴法云API服务模块 (核心变更：集中管理API相关逻辑)
        const BafaApiService = {
            // API基础配置 (API变更时只需修改这里)
            config: {
                apiUrl: "https://apis.bemfa.com",  // api域名
                endpoints: {
                    getData: "/va/getmsg",   // 获取数据接口
                    publish: "/va/postJsonMsg",       // 发布指令接口
                    getState: "/va/online"     // 设备状态接口
                },
                headers: {                          // 请求头配置
                    'Content-Type': 'application/json',
                    "Authorization": `Bearer ${BAFA_CONFIG.apiKey}`
                }
            },

            // 获取设备数据
            fetchData: async function(topic, clientId) {
                const url = `${this.config.apiUrl}${this.config.endpoints.getData}?topic=${topic}&uid=${clientId}&type=3`;
                
                try {
                    const response = await fetch(url);
                    if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);
                    
                    // 解析响应 (格式变更时修改这里)
                    const data = await response.json();
                    return this.parseDataResponse(data);
                } catch (error) {
                    console.error("获取数据失败:", error);
                    throw error;
                }
            },

            // 发送控制指令
            publishCommand: async function(command, config) {
                const url = `${this.config.apiUrl}${this.config.endpoints.publish}`;
                
                // 构造请求参数 (参数变更时修改这里)
                const formData = JSON.stringify({
                    'uid': config.apiKey,
                    'topic': config.airTopic,
                    'msg': JSON.stringify(command),
                    'type': 3
                });
					
                try {
                    const response = await fetch(url, {
                        method: "POST",
                        headers: this.config.headers,
                        body: formData
                    });

                    if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);
                    
                    // 解析发布响应 (格式变更时修改这里)
                    const result = await response.json();
	//console.log("434result:",result);
                    return this.parsePublishResponse(result);
                } catch (error) {
                    console.error("发送指令失败:", error);
                    throw error;
                }
            },

            // 检查设备状态
            checkState: async function(clientId, topic) {
                const url = `${this.config.apiUrl}${this.config.endpoints.getState}?uid=${clientId}&topic=${topic}&type=3`;
                console.log(url);
                try {
                    const response = await fetch(url);
                    return await response.json(); // 状态接口返回格式变更时修改
                } catch (error) {
                    console.error("检查状态失败:", error);
                    throw error;
                }
            },

            // 数据响应解析器 (返回格式变更时修改)
            parseDataResponse: function(rawData) {
	//console.log("457:",rawData)
                if (rawData.code === 0 && rawData.data) {
                    return {
                        success: true,
                        data: rawData.data
                    };
                }
                return {
                    success: false,
                    error: rawData.msg || "未知错误"
                };
            },

            // 发布响应解析器 (返回格式变更时修改)
            parsePublishResponse: function(rawResult) {
	//console.log("471:",rawResult.code)
                if (rawResult.code === 0) {
                    return { success: true };
                }
                return {
                    success: false,
                    error: rawResult || "发布失败"
                };
            }
        };
	
        // 自动刷新定时器ID
        let autoRefreshTimer = null;
        // 刷新间隔(毫秒) - 30秒
        const REFRESH_INTERVAL = 30000;
        
        // DOM 元素
        const tempElement = document.getElementById('temperature');
        const humidityElement = document.getElementById('humidity');
        const tempUpdateTime = document.getElementById('temp-update-time');
        const humUpdateTime = document.getElementById('hum-update-time');
        const acStatusElement = document.getElementById('ac-status');
        const acDetailsElement = document.getElementById('ac-details');
        const acModeElement = document.getElementById('ac-mode');
        const acTempElement = document.getElementById('ac-temp');
		const acFanElement = document.getElementById('ac-fan'); 
        const acIconElement = document.getElementById('ac-icon');
        const setTempElement = document.getElementById('set-temperature');
        const tempSliderElement = document.getElementById('temp-slider');
        const acPowerElement = document.getElementById('ac-power');
        const tempUpElement = document.getElementById('temp-up');
        const tempDownElement = document.getElementById('temp-down');
        const sendCommandElement = document.getElementById('send-command');
        const notificationElement = document.getElementById('notification');
        const notificationIconElement = document.getElementById('notification-icon');
        const notificationTextElement = document.getElementById('notification-text');
        const refreshBtn = document.getElementById('refresh-btn');
        const connectionStatus = document.getElementById('connection-status');
        const configPanel = document.getElementById('config-panel');
        const configBtn = document.getElementById('config-btn');
        const closeConfigBtn = document.getElementById('close-config');
        const saveConfigBtn = document.getElementById('save-config');
        const exportConfigBtn = document.getElementById('export-config');
        const importConfigBtn = document.getElementById('import-config');
        const importFileInput = document.getElementById('import-file');
        const configForm = document.getElementById('config-form');
        const clientIdInput = document.getElementById('client-id');
        const tempTopicInput = document.getElementById('temp-topic');
        const airTopicInput = document.getElementById('air-topic');
        const apiKeyInput = document.getElementById('api-key');
        const encryptPasswordInput = document.getElementById('encrypt-password');
        const bafaIdDisplay = document.getElementById('bafa-id-display');
        const topicsDisplay = document.getElementById('topics-display');
		const autoRefreshLabel = document.getElementById('auto-refresh-label');
        
        // 初始化图表
        const ctx = document.getElementById('environment-chart').getContext('2d');
        const envChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: timeLabels,
                datasets: [
                    {
                        label: '温度 (°C)',
                        data: tempHistory,
                        borderColor: '#165DFF',
                        backgroundColor: 'rgba(22, 93, 255, 0.1)',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: '湿度 (%)',
                        data: humidityHistory,
                        borderColor: '#36CFC9',
                        backgroundColor: 'rgba(54, 207, 201, 0.1)',
                        tension: 0.4,
                        fill: true,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: false,
                        title: {
                            display: true,
                            text: '温度 (°C)'
                        }
                    },
                    y1: {
                        beginAtZero: true,
                        position: 'right',
                        title: {
                            display: true,
                            text: '湿度 (%)'
                        },
                        grid: {
                            drawOnChartArea: false
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                    }
                }
            }
        });
        
        // 加密配置数据
        function encryptConfig(config, password) {
            if (!password || password.length < 6) {
                throw new Error("加密密码至少需要6个字符");
            }
            return CryptoJS.AES.encrypt(JSON.stringify(config), password).toString();
        }
        
        // 解密配置数据
        function decryptConfig(encryptedData, password) {
            try {
                const bytes = CryptoJS.AES.decrypt(encryptedData, password);
                const decryptedData = bytes.toString(CryptoJS.enc.Utf8);
                return JSON.parse(decryptedData);
            } catch (e) {
                throw new Error("解密失败，密码可能不正确");
            }
        }
        
        // 导出配置
        function exportConfig() {
            const password = encryptPasswordInput.value;
            if (!password) {
                showNotification("请设置加密密码", true);
                return;
            }
            
            // 获取表单数据
            const configData = {
                clientId: clientIdInput.value,
                tempTopic: tempTopicInput.value,
                airTopic: airTopicInput.value,
                apiKey: apiKeyInput.value,
                exportTime: new Date().toISOString()
            };
            
            // 验证必要字段
            if (!configData.clientId || !configData.apiKey) {
                showNotification("请填写巴法云ID和API密钥", true);
                return;
            }
            
            try {
                // 加密配置
                const encryptedData = encryptConfig(configData, password);
                
                // 创建下载文件
                const blob = new Blob([encryptedData], { type: 'application/octet-stream' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `bafa_config_${new Date().getTime()}.bafa`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                showNotification("配置已加密导出");
            } catch (error) {
                showNotification(error.message, true);
            }
        }
        
        // 导入配置
        function importConfig(file) {
            const password = encryptPasswordInput.value;
            if (!password) {
                showNotification("请输入加密密码", true);
                return;
            }
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    // 解密配置
                    const decryptedData = decryptConfig(e.target.result, password);
                    
                    // 验证配置数据
                    if (!decryptedData.clientId || !decryptedData.apiKey) {
                        throw new Error("导入的配置不完整");
                    }
                    
                    // 填充表单
                    clientIdInput.value = decryptedData.clientId || "";
                    tempTopicInput.value = decryptedData.tempTopic || "";
                    airTopicInput.value = decryptedData.airTopic || "";
                    apiKeyInput.value = decryptedData.apiKey || "";
                    
                    // 保存配置
                    saveConfig();
                    showNotification("配置已成功导入并应用");
                    
                    // 隐藏配置界面
                    configPanel.classList.add('hidden');
                } catch (error) {
                    showNotification(error.message, true);
                }
            };
            reader.readAsText(file);
        }
        
        // 保存配置到本地存储
        function saveConfig() {
            // 更新配置对象
            BAFA_CONFIG = {
                clientId: clientIdInput.value,
                tempTopic: tempTopicInput.value || "temp004",
                airTopic: airTopicInput.value || "aircd005",
                apiKey: apiKeyInput.value,
                apiUrl: "https://apis.bemfa.com"
            };
            
            // 保存到本地存储
            localStorage.setItem('bafa_config', JSON.stringify(BAFA_CONFIG));
            
            // 更新显示
            updateConfigDisplay();
            
            // 如果配置完整，开始数据交互
            if (BAFA_CONFIG.apiKey) {
                fetchFromBafaCloud();
                fetchAirConditionerStatus();
            }
            
            showNotification("配置已保存");
        }
        
        // 从本地存储加载配置
        function loadConfigFromStorage() {
            const savedConfig = localStorage.getItem('bafa_config');
            if (savedConfig) {
                try {
                    BAFA_CONFIG = JSON.parse(savedConfig);
                    
                    // 填充表单
                    clientIdInput.value = BAFA_CONFIG.clientId || "";
                    tempTopicInput.value = BAFA_CONFIG.tempTopic || "";
                    airTopicInput.value = BAFA_CONFIG.airTopic || "";
                    apiKeyInput.value = BAFA_CONFIG.apiKey || "";
                    
                    // 更新显示
                    updateConfigDisplay();
                    return true;
                } catch (e) {
                    console.error("加载配置失败:", e);
                    localStorage.removeItem('bafa_config'); // 移除损坏的配置
                }
            }
            return false;
        }
        
        // 更新配置显示
        function updateConfigDisplay() {
            if (BAFA_CONFIG.clientId) {
                bafaIdDisplay.textContent = `巴法云 ID: ${BAFA_CONFIG.clientId}`;
            } else {
                bafaIdDisplay.textContent = "巴法云 ID: 未配置";
            }
            
            if (BAFA_CONFIG.tempTopic && BAFA_CONFIG.airTopic) {
                topicsDisplay.innerHTML = `
                    <h3 class="font-medium">巴法云主题</h3>
                    <p class="text-gray-500 text-sm">温湿度: ${BAFA_CONFIG.tempTopic} | 空调: ${BAFA_CONFIG.airTopic}</p>
                `;
            } else {
                topicsDisplay.innerHTML = `
                    <h3 class="font-medium">巴法云主题</h3>
                    <p class="text-gray-500 text-sm">未配置</p>
                `;
            }
        }
		
		 // 启动自动刷新
		function startAutoRefresh() {
			// 先清除已有的定时器
			stopAutoRefresh();
            
            // 显示自动刷新指示器
            autoRefreshLabel.style.display = 'inline';
            
            // 设置新的定时器，每30秒执行一次
            autoRefreshTimer = setInterval(() => {
                console.log("自动刷新温湿度数据...");
                fetchFromBafaCloud();
                //fetchAirConditionerStatus();
            }, REFRESH_INTERVAL);
        }
        
        // 停止自动刷新
        function stopAutoRefresh() {
            if (autoRefreshTimer) {
                clearInterval(autoRefreshTimer);
                autoRefreshTimer = null;
                // 隐藏自动刷新指示器
                autoRefreshLabel.style.display = 'none';
            }
        }
        
        // 初始化模拟数据
        function initMockData() {
            // 生成过去12小时的模拟数据
            for (let i = 11; i >= 0; i--) {
                const now = new Date();
                now.setHours(now.getHours() - i);
                timeLabels.push(now.getHours() + ':00');
                
                // 生成有微小波动的温度数据
                const baseTemp = 25;
                const temp = (baseTemp + (Math.random() * 2 - 0.5)).toFixed(1);
                tempHistory.push(parseFloat(temp));
                
                // 生成湿度数据
                const baseHum = 60;
                const hum = (baseHum + (Math.random() * 10 - 5)).toFixed(1);
                humidityHistory.push(parseFloat(hum));
            }
            
            // 更新图表
            envChart.data.labels = timeLabels;
            envChart.data.datasets[0].data = tempHistory;
            envChart.data.datasets[1].data = humidityHistory;
            envChart.update();
            
            // 更新当前显示
            updateCurrentValues();
        }
        
        // 更新当前温湿度显示
        function updateCurrentValues() {
            if (tempHistory.length > 0) {
                const lastTemp = tempHistory[tempHistory.length - 1];
                tempElement.textContent = lastTemp;
                
                // 根据温度显示不同颜色
                if (lastTemp > 26) {
                    tempElement.classList.remove('text-cold', 'text-gray-700');
                    tempElement.classList.add('text-hot');
                } else if (lastTemp < 22) {
                    tempElement.classList.remove('text-hot', 'text-gray-700');
                    tempElement.classList.add('text-cold');
                } else {
                    tempElement.classList.remove('text-hot', 'text-cold');
                    tempElement.classList.add('text-gray-700');
                }
            }
            
            if (humidityHistory.length > 0) {
                humidityElement.textContent = humidityHistory[humidityHistory.length - 1];
            }
            
            // 更新时间
            const now = new Date();
            const timeStr = now.toLocaleTimeString();
            tempUpdateTime.textContent = `最后更新: ${timeStr}`;
            humUpdateTime.textContent = `最后更新: ${timeStr}`;
        }
        
        // 添加新的温湿度数据
        function addNewData() {
            const now = new Date();
            const timeStr = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
            
            // 移除最早的数据（保持12个数据点）
            if (timeLabels.length >= 12) {
                timeLabels.shift();
                tempHistory.shift();
                humidityHistory.shift();
            }
            
            // 添加新数据
            timeLabels.push(timeStr);
            
            // 基于当前温度生成微小波动
            let lastTemp = tempHistory.length > 0 ? tempHistory[tempHistory.length - 1] : 25;
            const newTemp = (lastTemp + (Math.random() * 0.6 - 0.3)).toFixed(1);
            tempHistory.push(parseFloat(newTemp));
            
            // 基于当前湿度生成微小波动
            let lastHum = humidityHistory.length > 0 ? humidityHistory[humidityHistory.length - 1] : 60;
            const newHum = (lastHum + (Math.random() * 2 - 1)).toFixed(1);
            humidityHistory.push(parseFloat(newHum));
            
            // 更新图表和显示
            envChart.data.labels = timeLabels;
            envChart.data.datasets[0].data = tempHistory;
            envChart.data.datasets[1].data = humidityHistory;
            envChart.update();
            
            updateCurrentValues();
        }
        
        // 更新空调状态显示
        function updateAcStatus() {
            if (isAcOn) {
                acStatusElement.textContent = '运行中';
                acStatusElement.classList.remove('text-gray-400');
                
                // 根据模式设置颜色和图标
                if (currentMode === 'auto') {
                    acStatusElement.classList.remove('text-hot', 'text-green-500', 'text-blue-500', 'text-purple-500');
                    acStatusElement.classList.add('text-gray-600');
                    acIconElement.innerHTML = '<i class="fa fa-refresh text-gray-600 text-xl"></i>';
                    acIconElement.className = 'p-3 rounded-full bg-gray-50';
                } else if (currentMode === 'cool') {
                    acStatusElement.classList.remove('text-hot', 'text-green-500', 'text-gray-600', 'text-purple-500');
                    acStatusElement.classList.add('text-cold');
                    acIconElement.innerHTML = '<i class="fa fa-snowflake-o text-cold text-xl"></i>';
                    acIconElement.className = 'p-3 rounded-full bg-blue-50';
                } else if (currentMode === 'dry') {
                    acStatusElement.classList.remove('text-hot', 'text-cold', 'text-gray-600', 'text-green-500');
                    acStatusElement.classList.add('text-purple-500');
                    acIconElement.innerHTML = '<i class="fa fa-tint text-purple-500 text-xl"></i>';
                    acIconElement.className = 'p-3 rounded-full bg-purple-50';
                } else if (currentMode === 'fan') {
                    acStatusElement.classList.remove('text-hot', 'text-cold', 'text-gray-600', 'text-purple-500');
                    acStatusElement.classList.add('text-green-500');
                    acIconElement.innerHTML = '<i class="fa fa-leaf text-green-500 text-xl"></i>';
                    acIconElement.className = 'p-3 rounded-full bg-green-50';
                } else if (currentMode === 'heat') {
                    acStatusElement.classList.remove('text-cold', 'text-green-500', 'text-gray-600', 'text-purple-500');
                    acStatusElement.classList.add('text-hot');
                    acIconElement.innerHTML = '<i class="fa fa-sun-o text-hot text-xl"></i>';
                    acIconElement.className = 'p-3 rounded-full bg-red-50';
                }
                
                // 更新详情
                acDetailsElement.classList.remove('hidden');
                acModeElement.textContent = modeToText(currentMode);
                acTempElement.textContent = currentTemp + '°C';
				acFanElement.textContent = fanToText(currentFan); 
            } else {
                acStatusElement.textContent = '未开启';
                acStatusElement.className = 'text-2xl font-bold text-gray-400';
                acIconElement.innerHTML = '<i class="fa fa-snowflake-o text-gray-400 text-xl"></i>';
                acIconElement.className = 'p-3 rounded-full bg-gray-50';
                acDetailsElement.classList.add('hidden');
            }
            
            // 更新控制面板状态
            acPowerElement.checked = isAcOn;
            setTempElement.textContent = currentTemp;
            updateTemperatureDisplay();
            
            // 更新模式按钮状态
            document.querySelectorAll('.ac-mode-btn').forEach(btn => {
                btn.classList.remove('active');
                if (btn.dataset.mode === currentMode) {
                    btn.classList.add('active');
                }
            });
            
            // 更新风速按钮状态
            document.querySelectorAll('.ac-fan-btn').forEach(btn => {
                btn.classList.remove('active');
                if (btn.dataset.fan === currentFan) {
                    btn.classList.add('active');
                }
            });
        }
        
        // 模式文本转换
        function modeToText(mode) {
            switch(mode) {
                case 'auto': return '自动';
                case 'cool': return '制冷';
                case 'dry': return '除湿';
                case 'fan': return '通风';
                case 'heat': return '制热';
                default: return '未知';
            }
        }
        
        // 代码转模式
        function codeToMode(code) {
            const modeMap = {
                '0': 'auto',   // 0为自动
                '1': 'cool',   // 1为制冷
                '2': 'dry',    // 2为除湿
                '3': 'fan',    // 3为通风
                '4': 'heat'    // 4为制热
            };
            return modeMap[code] || 'auto';
        }
		
		//风扇模式代码与文本映射 - 按新定义调整
        function fanToText(fan) {
            switch(fan) {
                case 'auto': return '自动';
                case 'low': return '低速';
                case 'medium': return '中速';
                case 'high': return '高速';
                default: return '未知';
            }
        }
        
        // 代码转风速
        function codeToFan(code) {
            const fanMap = {
                '0': 'auto',   // 0为自动
                '1': 'low',    // 1为低速
                '2': 'medium', // 2为中速
                '3': 'high'    // 3为高速
            };
            return fanMap[code] || 'low';
        }
        
        // 显示通知
        function showNotification(message, isError = false) {
            notificationTextElement.textContent = message;
            
            if (isError) {
                notificationIconElement.className = 'fa fa-exclamation-circle mr-2';
                notificationElement.classList.remove('bg-dark', 'bg-green-600');
                notificationElement.classList.add('bg-red-600');
            } else {
                notificationIconElement.className = 'fa fa-check-circle mr-2';
                notificationElement.classList.remove('bg-red-600', 'bg-green-600');
                notificationElement.classList.add('bg-dark');
            }
            
            // 显示通知
            notificationElement.classList.remove('translate-y-20', 'opacity-0');
            notificationElement.classList.add('translate-y-0', 'opacity-100');
            
            // 3秒后隐藏
            setTimeout(() => {
                notificationElement.classList.remove('translate-y-0', 'opacity-100');
                notificationElement.classList.add('translate-y-20', 'opacity-0');
            }, 3000);
        }
        
		
	        // 3. 使用API服务模块替换原有直接调用 (核心变更：调用方式修改)
			//查询温湿度
        async function fetchFromBafaCloud() {
		console.log("1038",isOnline);
			checkBafaConnection();
			console.log("1040");
            if (!BAFA_CONFIG.apiKey || !BAFA_CONFIG.tempTopic || isOnline == false) return;
            
            try {
                // 调用API服务获取数据 (替代原有直接fetch)
                const result = await BafaApiService.fetchData(
                    BAFA_CONFIG.tempTopic, 
                    BAFA_CONFIG.apiKey
                );
 //console.log("974",result);
                if (result.success && result.data) {
					const [,temperature,humidity,newStatus] = result.data[0].msg.split('#');
                    const newTemp = parseFloat(temperature);
					const newHum = parseFloat(humidity);
                    
                    
                    if (validateEnvData(newTemp, newHum)) {
                        addRealData(newTemp, newHum);
                        //connectionStatus.innerHTML = '<span class="w-2 h-2 rounded-full bg-green-500 mr-2"></span><span>已连接</span><span id="auto-refresh-label" class="ml-2 text-xs text-gray-500 auto-refresh-indicator">(自动刷新中)</span>';
                    } else {
                        throw new Error("获取到无效的温湿度数据");
                    }
                } else {
                    connectionStatus.innerHTML = `<span class="w-2 h-2 rounded-full bg-red-500 mr-2"></span><span>${result.error}</span><span id="auto-refresh-label" class="ml-2 text-xs text-gray-500 auto-refresh-indicator">(自动刷新中)</span>`;
                }
            } catch (error) {
                console.error("获取数据失败:", error);
                connectionStatus.innerHTML = '<span class="w-2 h-2 rounded-full bg-red-500 mr-2"></span><span>连接失败</span><span id="auto-refresh-label" class="ml-2 text-xs text-gray-500 auto-refresh-indicator">(自动刷新中)</span>';
            }
        }
        
		//查询空调状态
        async function fetchAirConditionerStatus() {
            if (!BAFA_CONFIG.apiKey || !BAFA_CONFIG.airTopic) return;
            
            connectionStatus.innerHTML = '<span class="w-2 h-2 rounded-full bg-yellow-500 mr-2 animate-pulse"></span><span>加载中...</span><span id="auto-refresh-label" class="ml-2 text-xs text-gray-500 auto-refresh-indicator">(自动刷新中)</span>';
            
            try {
                // 调用API服务获取空调状态
                const result = await BafaApiService.fetchData(
                    BAFA_CONFIG.airTopic, 
                    BAFA_CONFIG.apiKey
                );
                console.log(result);
                if (result.success && result.data && result.data[0].msg) {
                    const acData = JSON.parse(result.data[0].msg);
                    
                    if (validateAcData(acData)) {
                        isAcOn = acData.power === "1" || acData.power === 1;
                        currentMode = codeToMode(acData.mode);
                        currentTemp = parseInt(acData.temp) || 26;
                        currentFan = codeToFan(acData.fan);
                        updateAcStatus();
                    } else {
                        throw new Error("获取到无效的空调状态数据");
                    }
                } else {
                    showNotification(result.error || "未获取到空调状态数据", true);
                }
            } catch (error) {
                console.error("获取空调状态错误:", error);
                showNotification("获取空调状态失败", true);
            } finally {
                
				checkBafaConnection();
            }
        }
        
		//发送控制指令
        async function sendAcCommand() {
            if (!BAFA_CONFIG.apiKey) {
                showNotification("请先配置巴法云信息", true);
                configPanel.classList.remove('hidden');
                return;
            }

            const commandData = {
                power: isAcOn ? "1" : "0",
                mode: modeToCode(currentMode),
                temp: currentTemp.toString(),
                fan: fanToCode(currentFan),
                time: new Date().getTime()
            };

            const sendBtn = document.getElementById('send-command');
            const originalText = sendBtn.innerHTML;
            sendBtn.disabled = true;
            sendBtn.innerHTML = '<i class="fa fa-circle-o-notch fa-spin mr-2"></i> 发送中...';

            try {
                // 调用API服务发送指令
                const result = await BafaApiService.publishCommand(commandData, BAFA_CONFIG);
console.log(commandData, BAFA_CONFIG);
                if (result.success) {
                    showNotification("控制指令发送成功");
                } else {
                    showNotification(`发送失败: ${result.error}`, true);
                }
            } catch (error) {
                console.error("发送指令失败:", error);
                showNotification(`发送失败: ${error.message}`, true);
            } finally {
                sendBtn.disabled = false;
                sendBtn.innerHTML = originalText;
            }
        }
        
		//检查连接状态
        async function checkBafaConnection() {
            if (!BAFA_CONFIG.apiKey || !BAFA_CONFIG.airTopic) return;
            
            try {
                // 调用API服务检查状态
                const state = await BafaApiService.checkState(BAFA_CONFIG.apiKey, BAFA_CONFIG.airTopic);
				console.log("1151",state.data);
                if (state.data) {
                    connectionStatus.innerHTML = '<span class="w-2 h-2 rounded-full bg-green-500 mr-2"></span><span> 遥控设备在线</span><span id="auto-refresh-label" class="ml-2 text-xs text-gray-500 auto-refresh-indicator">(自动刷新中)</span>';
					isOnline = true;
				} else {
                    connectionStatus.innerHTML = '<span class="w-2 h-2 rounded-full bg-yellow-500 mr-2"></span><span>遥控设备离线</span><span id="auto-refresh-label" class="ml-2 text-xs text-gray-500 auto-refresh-indicator">(自动刷新中)</span>';
					isOnline = false;
				}
            } catch (error) {
                connectionStatus.innerHTML = '<span class="w-2 h-2 rounded-full bg-red-500 mr-2"></span><span>连接失败</span><span id="auto-refresh-label" class="ml-2 text-xs text-gray-500 auto-refresh-indicator">(自动刷新中)</span>';
            }
        }	
		
		
		

        
        // 验证环境数据合法性
        function validateEnvData(temp, hum) {
            // 温度范围：-10°C 到 50°C
            // 湿度范围：0% 到 100%
            return !isNaN(temp) && !isNaN(hum) && 
                   temp >= -10 && temp <= 50 && 
                   hum >= 0 && hum <= 100;
        }
        
        // 验证空调数据合法性
        function validateAcData(acData) {
            // 检查是否包含必要字段
            if (!acData || !acData.power || !acData.mode || !acData.temp) {
                return false;
            }
            
            // 校验温度范围（16-30°C）
            const temp = parseInt(acData.temp);
            if (isNaN(temp) || temp < 16 || temp > 30) {
                return false;
            }
            
            // 校验模式是否合法（0-4）
            const mode = acData.mode.toString();
            if (!['0', '1', '2', '3','4'].includes(mode)) {
                return false;
            }
            
            // 校验风速是否合法（0-3）
            const fan = acData.fan ? acData.fan.toString() : '0';
            if (!['0', '1', '2','3'].includes(fan)) {
                return false;
            }
            
            return true;
        }
        
        // 添加真实数据到图表
        function addRealData(temp, hum) {
            const now = new Date();
            const timeStr = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
            
            // 保持数据点数量
            if (timeLabels.length >= 12) {
                timeLabels.shift();
                tempHistory.shift();
                humidityHistory.shift();
            }
            
            timeLabels.push(timeStr);
            tempHistory.push(temp);
            humidityHistory.push(hum);
            
            // 更新图表和显示
            envChart.data.labels = timeLabels;
            envChart.data.datasets[0].data = tempHistory;
            envChart.data.datasets[1].data = humidityHistory;
            envChart.update();
            
            updateCurrentValues();
        }
        

        
        // 辅助函数: 将模式转换为设备可识别的代码
        function modeToCode(mode) {
            const modeMap = {
                'auto': '0',   // 自动对应0
                'cool': '1',   // 制冷对应1
                'dry': '2',    // 除湿对应2
                'fan': '3',    // 通风对应3
                'heat': '4'    // 制热对应4
            };
            return modeMap[mode] || '0'; // 默认自动模式
        }
        
        // 辅助函数: 将风速转换为设备可识别的代码
        function fanToCode(fan) {
            const fanMap = {
                 'auto': '0',   // 自动对应0
                'low': '1',    // 低速对应1
                'medium': '2', // 中速对应2
                'high': '3'    // 高速对应3
            };
            return fanMap[fan] || '0'; // 默认低速
        }
        
        // 更新温度显示
        function updateTemperatureDisplay() {
            setTempElement.textContent = currentTemp;
            
            // 计算滑块位置 (16-30度对应0-100%)
            const percentage = ((currentTemp - 16) / (30 - 16)) * 100;
            tempSliderElement.style.width = percentage + '%';
            
            // 更新空调显示
            if (isAcOn) {
                acTempElement.textContent = currentTemp + '°C';
            }
        }
        
		 // 页面卸载时清理定时器
        window.addEventListener('beforeunload', () => {
            stopAutoRefresh();
        });
		
        // 事件监听器
        document.addEventListener('DOMContentLoaded', () => {
            // 初始化数据
            //initMockData();
            
            // 尝试从本地存储加载配置
            const configLoaded = loadConfigFromStorage();
			
            
            // 如果配置已加载，不显示配置界面；否则显示
            if (!configLoaded || !BAFA_CONFIG.apiKey) {
                configPanel.classList.remove('hidden');
            } else {
                // 已加载配置，获取设备状态
                fetchAirConditionerStatus();
                //fetchFromBafaCloud();
				startAutoRefresh();
            }
            
            // 配置按钮点击事件
            configBtn.addEventListener('click', () => {
                configPanel.classList.remove('hidden');
            });
            
            // 关闭配置面板
            closeConfigBtn.addEventListener('click', () => {
                configPanel.classList.add('hidden');
            });
            
            // 保存配置
            saveConfigBtn.addEventListener('click', saveConfig);
            
            // 导出配置
            exportConfigBtn.addEventListener('click', exportConfig);
            
            // 导入配置按钮
            importConfigBtn.addEventListener('click', () => {
                importFileInput.click();
            });
            
            // 导入文件选择
            importFileInput.addEventListener('change', (e) => {
                if (e.target.files && e.target.files[0]) {
                    importConfig(e.target.files[0]);
                    // 重置输入，允许重复选择同一个文件
                    e.target.value = '';
                }
            });
            
            // 点击配置面板外部关闭
            configPanel.addEventListener('click', (e) => {
                if (e.target === configPanel) {
                    configPanel.classList.add('hidden');
                }
            });
            
            // 温度调节按钮
            tempUpElement.addEventListener('click', () => {
                if (currentTemp < 30) {
                    currentTemp++;
                    updateTemperatureDisplay();
                }
            });
            
            tempDownElement.addEventListener('click', () => {
                if (currentTemp > 16) {
                    currentTemp--;
                    updateTemperatureDisplay();
                }
            });
            
            // 空调电源开关
            acPowerElement.addEventListener('change', () => {
                isAcOn = acPowerElement.checked;
                updateAcStatus();
            });
            
            // 模式选择按钮
            document.querySelectorAll('.ac-mode-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    // 移除所有按钮的active类
                    document.querySelectorAll('.ac-mode-btn').forEach(b => {
                        b.classList.remove('active');
                    });
                    
                    // 给当前点击的按钮添加active类
                    btn.classList.add('active');
                    
                    // 更新当前模式
                    currentMode = btn.dataset.mode;
                    updateAcStatus();
                });
            });
            
            // 风速选择按钮
            document.querySelectorAll('.ac-fan-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    // 移除所有按钮的active类
                    document.querySelectorAll('.ac-fan-btn').forEach(b => {
                        b.classList.remove('active');
                    });
                    
                    // 给当前点击的按钮添加active类
                    btn.classList.add('active');
                    
                    // 更新当前风速
                    currentFan = btn.dataset.fan;
					updateAcStatus();
                });
            });
            
            // 发送指令按钮
            sendCommandElement.addEventListener('click', sendAcCommand);
            
            // 刷新按钮
            refreshBtn.addEventListener('click', () => {
                // 添加旋转动画
                refreshBtn.querySelector('i').classList.add('fa-spin');
                
                // 刷新数据
                if (BAFA_CONFIG.apiKey) {
                    fetchFromBafaCloud();
                    fetchAirConditionerStatus();
					// 手动刷新后，重置自动刷新计时器
                    startAutoRefresh();
                } else {
                    addNewData();
                    showNotification("请先配置巴法云信息", true);
                }
                
                // 1秒后停止动画
                setTimeout(() => {
                    refreshBtn.querySelector('i').classList.remove('fa-spin');
                }, 1000);
            });
        });
        
        // 自定义按钮样式
        const style = document.createElement('style');
        style.textContent = `
            .ac-mode-btn, .ac-fan-btn {
                background-color: #f5f5f5;
                border: none;
                border-radius: 10px;
                padding: 12px 5px;
                transition: all 0.2s ease;
                cursor: pointer;
            }
            
            .ac-mode-btn.active, .ac-fan-btn.active {
                background-color: #e8f3ff;
                color: #165DFF;
                font-weight: 500;
            }
            
            .ac-mode-btn:hover, .ac-fan-btn:hover {
                background-color: #e5e7eb;
            }
            
            .active-chart-period {
                background-color: #165DFF;
                color: white;
            }
            
            #temp-up:hover, #temp-down:hover {
                background-color: #e5e7eb;
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>
